
package com.treeman.navi;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.treeman.navi.marker.MarkerType.markerType;
import com.treeman.navi.rest.RestClient;
import com.treeman.navi.rest.RestClient.HttpConnectionStatus;
import com.treeman.navi.rest.RestClient.RequestMethod;
import com.treeman.utilities.Utilities;


public class MarkerActivity extends Activity
{

    public final static String TAG = "MarkerActivity";

    private TextView textViewAddress = null;

    private EditText editTextName = null;
    private EditText editTextDescription = null;

    private Spinner spinnerPoi = null;

    private Double latitude = 0d;
    private Double longitude = 0d;

    private int REQUEST_CODE = 0;

    private String[] markerTypes;

    private Long markerId = -1L;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
	Log.v(TAG, "Marker opened.");
	super.onCreate(savedInstanceState);

	setContentView(R.layout.marker);

	Intent request = getIntent();

	REQUEST_CODE = request.getExtras().getInt("REQUEST_CODE");

	longitude = request.getExtras().getDouble("Longitude", 0d);
	latitude = request.getExtras().getDouble("Latitude", 0d);

	// VIEW

	editTextDescription = (EditText) findViewById(R.id.editText_markerDescription);
	editTextName = (EditText) findViewById(R.id.editText_markerName);

	textViewAddress = (TextView) findViewById(R.id.textView_markerAddress);

	spinnerPoi = (Spinner) findViewById(R.id.spinner_markerPoi);

	// DISPLAY INFO
	if (longitude != 0d && latitude != 0d)
	{
	    Geocoder geocoder = new Geocoder(this);

	    try
	    {
		List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);

		if (addresses != null)
		{
		    Address returnedAddress = addresses.get(0);
		    StringBuilder strReturnedAddress = new StringBuilder("");
		    for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++)
		    {
			strReturnedAddress.append(returnedAddress.getAddressLine(i));
			if (i + 1 != returnedAddress.getMaxAddressLineIndex()) strReturnedAddress.append(", ");
		    }
		    textViewAddress.setText(strReturnedAddress.toString());
		}
	    }
	    catch (IOException ex)
	    {
		Log.e(TAG, "Marker error : ", ex);
	    }
	}

	if (REQUEST_CODE == CustomMapActivity.REQUEST_CODE_MARKER_EDIT)
	{
	    editTextName.setText(request.getExtras().getString("name"));
	    editTextDescription.setText(request.getExtras().getString("description"));

	    markerId = request.getExtras().getLong("id");

	    TextView textViewHeader = (TextView) findViewById(R.id.textView_markerHeader);
	    textViewHeader.setText("" + getString(R.string.marker_edit_header));
	}

	markerTypes = Utilities.enumToStringArray(markerType.values());

	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, markerTypes);
	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

	spinnerPoi.setAdapter(adapter);
    }

    @Override
    protected void onDestroy()
    {
	Log.v(TAG, "Marker closed.");
	super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
	if ((keyCode == KeyEvent.KEYCODE_BACK))
	{
	    try
	    {

		Bundle bundle = new Bundle();

		// bundle.putString("info", "route search close");

		Intent i = new Intent();

		i.putExtras(bundle);

		setResult(CustomMapActivity.RESULT_CODE_MARKER_CANCEL, i);

		finish();
	    }
	    catch (Exception ex)
	    {
		Log.e(TAG, TAG + " Error : ", ex);
	    }
	}
	return super.onKeyDown(keyCode, event);
    }

    public void saveMarkerClick(View v)
    {
	try
	{

	    String type = markerTypes[(int) spinnerPoi.getSelectedItemId()];
	    String name = editTextName.getText().toString();
	    String description = editTextDescription.getText().toString();
	    String address = textViewAddress.getText().toString();

	    if (name.length() > 0 && description.length() > 0)
	    {
		Log.i(TAG, "Marker : " + name + ", " + description + ", " + address + ", " + type);

		Handler handler = new Handler()
		{

		    @Override
		    public void handleMessage(Message msg)
		    {
			if (msg.what == HttpConnectionStatus.START.ordinal())
			{
			    Log.i(TAG, "Starting connection for marker add/edit ... ");

			    try
			    {

			    }
			    catch (Exception ex)
			    {
				Log.e(TAG, " START error : ", ex);
			    }
			}
			if (msg.what == HttpConnectionStatus.SUCCESS.ordinal())
			{
			    Log.i(TAG, "Connection success! Add/Edit.");

			    try
			    {

				RestClient restClient = (RestClient) msg.obj;

				String response = restClient.getResponse();

				Log.i(TAG, "Response: " + response + "( RESPONSE CODE " + restClient.getResponseCode() + ")");

			    }
			    catch (Exception ex)
			    {
				Log.e(TAG, " SUCCESS error : ", ex);
			    }
			}
			if (msg.what == HttpConnectionStatus.ERROR.ordinal())
			{
			    Log.i(TAG, "Connection error while add/edit!");
			    try
			    {

				RestClient restClient = (RestClient) msg.obj;

				String response = restClient.getResponse();

				Log.i(TAG, "Response: " + response + "( RESPONSE CODE " + restClient.getResponseCode() + ")");

			    }
			    catch (Exception ex)
			    {
				Log.e(TAG, " CONNECTION error : ", ex);
			    }
			}

			Bundle bundle = new Bundle();

			Intent i = new Intent();

			i.putExtras(bundle);

			if (REQUEST_CODE == CustomMapActivity.REQUEST_CODE_MARKER_ADD)
			{
			    setResult(CustomMapActivity.RESULT_CODE_MARKER_ADD_OK, i);
			}
			else if (REQUEST_CODE == CustomMapActivity.REQUEST_CODE_MARKER_EDIT)
			{
			    setResult(CustomMapActivity.RESULT_CODE_MARKER_EDIT_OK, i);
			}

			finish();

		    }
		};
		if (REQUEST_CODE == CustomMapActivity.REQUEST_CODE_MARKER_ADD)
		{
		    RestClient restClient = new RestClient(getString(R.string.server_url) + "api/me/markers", handler);

		    try
		    {

			ProgressDialog progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Dodawanie znacznika ...");
			progressDialog.setCancelable(false);

			restClient.setProgressDialog(progressDialog);

			restClient.Execute(RequestMethod.POST);

		    }
		    catch (Exception ex)
		    {
			Log.e(TAG, " RestClient error : ", ex);
			Bundle bundle = new Bundle();
			Intent i = new Intent();
			i.putExtras(bundle);
			setResult(CustomMapActivity.RESULT_CODE_MARKER_CANCEL, i);
			finish();
		    }
		}
		if (REQUEST_CODE == CustomMapActivity.REQUEST_CODE_MARKER_EDIT)
		{
		    RestClient restClient = new RestClient(getString(R.string.server_url) + "api/me/markers/" + markerId, handler);

		    try
		    {
			ProgressDialog progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Edytowanie znacznika ...");
			progressDialog.setCancelable(false);

			restClient.setProgressDialog(progressDialog);

			restClient.AddHeader("Accept", "application/json");

			restClient.Execute(RequestMethod.PUT);

		    }
		    catch (Exception ex)
		    {
			Log.e(TAG, " RestClient error : ", ex);
			Bundle bundle = new Bundle();
			Intent i = new Intent();
			i.putExtras(bundle);
			setResult(CustomMapActivity.RESULT_CODE_MARKER_CANCEL, i);
			finish();
		    }
		}
	    }

	}
	catch (Exception ex)
	{
	    Log.e(TAG, TAG + " Error : ", ex);
	}
    }
}
